<template>
	<view>
		<template v-if="name">
			<view class="bgw item font-bold font-32">【{{name}}】</view>
			<view class="blank20"></view>
		</template>
		<template v-for="(v,i) in list">
			<view class="bgw">
				<view class="item">
					<view class="flex">
						<view class="flex-1 flex">
							<view class="font-bold font-32">
								{{titleList[i].title}}
							</view>
							<view class="ml15" @click="info(i)">
								<u-icon name="question-circle" color="#675f91" size="20"></u-icon>
							</view>
						</view>
						<view class="" v-if="!isReadonly">
							<u-radio-group v-model="radioValue[i]" placement="row">
								<u-radio activeColor="#00AD2E" label="合格" name="y"></u-radio>
								<view class=" ml10 mr10"></view>
								<u-radio activeColor="#00AD2E" label="不合格" name="n"></u-radio>
							</u-radio-group>
						</view>
						<view class="" v-if="isReadonly">
							<view class="text-green font-bold" v-if="v.check_result == 'y'">
								合格
							</view>
							<view class="text-red font-bold" v-if="v.check_result == 'n'">
								不合格
							</view>
						</view>
					</view>
				</view>
				<template v-if="isReadonly">
					<template v-if="fileList[i].length>0">
						<u-line></u-line>
						<view class="blank20"></view>
						<view class="wrapper" >
							<u-album :urls="fileList[i]"></u-album>
						</view>
						<view class="blank20"></view>
					</template>
					<template v-if="v.check_note">
						<u-line></u-line>
						<view class="blank20"></view>
						<view class="wrapper font-32">
							<text class="text-gray">
								备注：
							</text>
							<text>{{v.check_note}}</text>
						</view>
						<view class="blank20"></view>
					</template>
				</template>
				<template v-if="!isReadonly">
					<u-line></u-line>
					<view class="blank20"></view>
					<view class="wrapper">
						<u-upload :fileList="fileList[i]" @afterRead="afterRead" @delete="deletePic" :name="i+''" multiple
							:maxCount="3"></u-upload>
					</view>
					<view class="blank20"></view>
					<u-line></u-line>
					<view class="flex wrapper">
						<view class="text-gray font-32">
							备注：
						</view>
						<view class="flex-1">
							<view class="blank20"></view>
							<input style="font-size: 36upx;text-align: left;" class="font-bold" v-model="checkNote[i]" type="text" placeholder="请输入备注" />
							<view class="blank20"></view>
						</view>
					</view>
				</template>
			</view>
			<view class="blank20"></view>
		</template>


		<nodata v-if="loadingStatus == 'end' && list.length == 0"></nodata>
		<u-gap height="90"></u-gap>
		<cover-view class="fixed-bottom bgw" v-if="list.length != 0 && !isReadonly">
			<cover-view class="blank20"></cover-view>
			<cover-view class="wrapper">
				<cover-view class="flex">
					<cover-view class="flex-1">
						<cover-view class="submit-btn" @click="submitForm">确认</cover-view>
					</cover-view>
				</cover-view>
			</cover-view>
			<cover-view class="blank20"></cover-view>
		</cover-view>

	</view>
</template>

<script>
	import {
		get_or_create_one_sop_review,
		get_one_sop_review_detail,
		common_create,
		common_write,
		upload_attachment,
		unlink_attachment
	} from '@/common/api.js';
	import nodata from '@/components/nodata.vue';
	export default {
		data() {
			return {
				id:null,
				isReadonly: false,
				role: null,
				userInfo: null,
				list: [],
				titleList:[],
				fileList: [],
				radioValue:[],
				checkNote:[],
				loadingStatus: '',
				process_check_detail_list_model_name:'',
				process_check_record_list_model_name:'',
				process_check_record:null,
				name:''
			}
		},
		components: {
			nodata
		},
		methods: {
			info(i) {
				this.$store.dispatch('modal', {
					title: this.titleList[i].title,
					content: this.titleList[i].desc,
					showCancel: false,
					confirmText: '知道了'
				}).then(() => {

				}).catch(() => {

				}).finally(() => {

				})
			},
			async submitForm() {
				// console.log(this.process_check_detail_list_model_name);
				uni.showLoading({
					title: '提交中'
				});
				if((this.process_check_record.id+'').startsWith('virtual_')){
					try{
						await this.create_process_check_record();
					}catch(e){
						uni.hideLoading();
						uni.$u.toast(e);
						return;
					}
				}
				this.list.forEach((v,i)=>{
					v.check_result = this.radioValue[i];
					v.check_note = (this.checkNote[i]+'').trim();
				})
				let createList = this.list.filter(v=>(v.id+'').startsWith('virtual_'));
				let writeList = this.list.filter(v=>!(v.id+'').startsWith('virtual_'));
				
				try{
					if(createList.length>0){
						createList = createList.map(v=>{
							return {
								check_result:v.check_result,
								check_note:v.check_note,
								id:v.id,
								process_check_record_id:v.process_check_record_id,
								sop_id:v.sop_id
							}
						})
						await this.create_process_check_detail(createList);
					}
					if(writeList.length>0){
						writeList = writeList.map(v=>{
							return {
								check_result:v.check_result,
								check_note:v.check_note,
								id:v.id,
								process_check_record_id:v.process_check_record_id,
								sop_id:v.sop_id
							}
						})
						await this.write_process_check_detail(writeList);
					}
					uni.$u.toast('提交成功');
					setTimeout(() => {
						uni.navigateBack();
					}, 2000);
					
				}catch(e){
					uni.hideLoading();
					uni.$u.toast(e);
					return;
				}
			},
			async create_process_check_record(){
				let data = JSON.parse(JSON.stringify(this.process_check_record));
				await common_create({
					model_name: this.process_check_record_list_model_name,
					vals_list: [data]
				}).then((res) => {
					let newId = res.result[data.id].id;
					this.process_check_record.id = newId;
					this.list.forEach(v=>{
						v.process_check_record_id = newId;
					})
				}).catch(() => {
					throw 'create_process_check_record 失败';
				}).finally(() => {
					
				})
			},
			async create_process_check_detail(vals_list){
				await common_create({
					model_name: this.process_check_detail_list_model_name,
					vals_list:vals_list
				}).then((res) => {
					for (let oldId in res.result){
						let _i = this.list.findIndex(d=>d.id == oldId);
						this.list[_i].id = res.result[oldId].id;
					}
					// console.log(res);
				}).catch(() => {
					throw 'create_process_check_detail 失败';
				}).finally(() => {
					
				})
			},
			async write_process_check_detail(vals_list){
				await common_write({
					model_name: this.process_check_detail_list_model_name,
					vals_list:vals_list
				}).then((res) => {
					console.log(res);
				}).catch(() => {
					throw 'write_process_check_detail 失败';
				}).finally(() => {
					
				})
			},
			// 删除图片
			async deletePic(event) {
				console.log(event)
				let filesIndex = Number(event.name);
				let imgIndex = Number(event.index);
				await this.deleteFilePromise(imgIndex, filesIndex);
				this.fileList[filesIndex].splice(imgIndex, 1);
			},
			deleteFilePromise(imgIndex, filesIndex) {
				let res_id = this.list[filesIndex].id;
				let res_model = this.process_check_detail_list_model_name;
				let res_field = this.fileList[filesIndex][imgIndex].fname;
				return unlink_attachment({
					res_model,
					res_id,
					res_field,
					csrf_token: this.userInfo.csrf_token
				}).then((res) => {
					console.log(res);
				})
			},

			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let filesIndex = Number(event.name);
				let id = this.list[filesIndex].id;
				let fileListLen = this.fileList[filesIndex].length;
				let allFnameList = ['image1','image2','image3'];
				let fnames = [];
				lists.map((item) => {
					let __fnameList = this.fileList[filesIndex].map(v=>v.fname);
					let fname = allFnameList.find(v=>!__fnameList.includes(v));
					this.fileList[filesIndex].push({
						...item,
						status: 'uploading',
						message: '上传中',
						fname
					});
					fnames.push(fname);
				})
				let errorFnames = [];//上传错误的图片
				for (let i = 0; i < lists.length; i++) {
					let result;
					try{
						result = await this.uploadFilePromise(lists[i].url, fnames[i], filesIndex);
					}catch(e){
						result = false;
						errorFnames.push(fnames[i]);
					}
					console.log(result);
					if(result){
						let item = this.fileList[filesIndex][fileListLen];
						this.fileList[filesIndex].splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '',
							url: result
						}))
					}
					fileListLen++
				}
				if(errorFnames.length>0){
					uni.$u.toast('图片上传错误');
				}
				let filter_arr = this.fileList[filesIndex].filter(v=>{
					if(errorFnames.includes(v.fname)){
						return false;
					}else{
						return true
					}
				});
				this.$set(this.fileList,filesIndex,filter_arr);
			},
			async uploadFilePromise(url, fname, filesIndex) {
				if((this.process_check_record.id+'').startsWith('virtual_')){
					try{
						await this.create_process_check_record();
					}catch(e){
						uni.$u.toast(e);
						throw e;
					}
				}
				if((this.list[filesIndex].id+'').startsWith('virtual_')){
					try{
						await this.create_process_check_detail([this.list[filesIndex]]);
					}catch(e){
						uni.$u.toast(e);
						throw e;
					}
				}
				let res_id = this.list[filesIndex].id;
				let res_model = this.process_check_detail_list_model_name;
				return upload_attachment(url, {
					res_model,
					res_id,
					fname,
					csrf_token: this.userInfo.csrf_token,
				}).then((res) => {
					return res;
					// console.log(res);
				})
			},
			getData() {
				uni.showLoading({
					title: '加载中'
				});
				this.loadingStatus = 'loading';
				if(this.isReadonly){
					get_one_sop_review_detail({
						process_check_record_id:this.id
					}).then((res) => {
						let {sop_review_list,sop_detail} = res.result;
						this.list = sop_review_list.map(v=>{
							return {
								id:v.id,
								check_result:v.check_result,
								check_note:v.check_note || '',
								sop_id:v.sop_id[0],
								process_check_record_id:v.process_check_record_id[0]
							}
						});
						let sop_detail_obj = this.toObj(sop_detail,'id');
						let titleList = [];
						this.fileList = [];
						
						this.list.forEach((v,i)=>{
							titleList.push({
								title:sop_detail_obj[v.sop_id].sop_type,
								desc:sop_detail_obj[v.sop_id].sop,
							})
							this.fileList.push([]);
							if(sop_review_list[i].image1){
								this.fileList[i].push(sop_review_list[i].image1);
							}
							if(sop_review_list[i].image2){
								this.fileList[i].push(sop_review_list[i].image1);
							}
							if(sop_review_list[i].image3){
								this.fileList[i].push(sop_review_list[i].image3);
							}
						});
						this.titleList = titleList;
					}).catch(() => {
						uni.hideLoading();
					}).finally(() => {
						this.loadingStatus = 'end';
						uni.hideLoading();
						uni.stopPullDownRefresh();
					})
				}else{
					get_or_create_one_sop_review({
						sop_review_id:this.id
					}).then((res) => {
						let {process_check_detail_list,process_check_record_list,sop_detail} = res.result;
						this.process_check_detail_list_model_name = process_check_detail_list.model_name;
						this.process_check_record_list_model_name = process_check_record_list.model_name;
						let sop_detail_obj = this.toObj(sop_detail,'id');
						let list = process_check_detail_list.vals_list;
						this.radioValue = list.map(v=>'');
						this.fileList = list.map(v=>[]);
						this.checkNote = list.map(v=>'');
						let titleList = [];
						this.list = list;
						list.forEach((v,i)=>{
							titleList.push({
								title:sop_detail_obj[v.sop_id].sop_type,
								desc:sop_detail_obj[v.sop_id].sop,
							})
							this.$set(this.radioValue,i,v.check_result);
							this.$set(this.checkNote,i,(v.check_note||''));
							let imgs = [];
							if(v.image1){
								imgs.push({url:v.image1,fname:'image1'});
							}
							if(v.image2){
								imgs.push({url:v.image2,fname:'image2'});
							}
							if(v.image3){
								imgs.push({url:v.image3,fname:'image3'});
							}
							this.$set(this.fileList,i,imgs);
						});
						this.titleList = titleList;
						this.process_check_record = process_check_record_list.vals_list[0];
					}).catch(() => {
						uni.hideLoading();
					}).finally(() => {
						this.loadingStatus = 'end';
						uni.hideLoading();
						uni.stopPullDownRefresh();
					})
				}
				
				
				// this.list = [{
				// 		name: '健康证公示'
				// 	},
				// 	{
				// 		name: '健康证明'
				// 	},
				// ];
				// this.radioValue = ['1', '1'];

				// if (this.isReadonly) {
				// 	this.fileList = [
				// 		[
				// 			'https://cdn.uviewui.com/uview/swiper/1.jpg',
				// 			'https://cdn.uviewui.com/uview/swiper/1.jpg',
				// 		],
				// 		['https://cdn.uviewui.com/uview/swiper/1.jpg'],
				// 	]
				// } else {
				// 	this.fileList = [
				// 		[],
				// 		[]
				// 	]
				// }
			}
		},
		onShow() {
			
		},
		onLoad(d) {
			this.name = d.name;
			if (d.isReadonly) {
				this.isReadonly = true;
				uni.setNavigationBarTitle({
					title: '结果明细'
				});
			}else{
				uni.setNavigationBarTitle({
					title: '检查'
				});
			}
			if(!d.id){
				d.id = '63';
			}
			if(d.id){
				this.id = Number(d.id);
			}
			try {
				this.role = this.$store.getters.get_role;
				this.userInfo = this.$store.getters.get_userInfo;
				this.getData();
			} catch (e) {
				uni.reLaunch({
					url: '/pages/login/login'
				});
			}

		}
	}
</script>

<style lang="scss" scoped>
	/deep/.item {
		padding: 20upx 30upx;
	}

	.fixed-bottom {
		border-top: 1px solid #ebedf0;
		z-index: 9999;
	}

	.submit-btn {
		color: #ffffff;
		background-color: #5ac725;
		border-radius: 3px;
		border: 1px solid #5ac725;
		height: 40px;
		line-height: 40px;
		text-align: center;
	}
</style>